<?php

namespace backend\controllers;

use app\models\AsrPlan;
use app\models\search\AsrPlanSearch;
use common\helps\AsrSearch;
use common\helps\Tools;
use Yii;
use yii\data\Pagination;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;

/**
 * AsrPlanController implements the CRUD actions for AsrPlan model.
 */
class AsrPlanController extends CommonController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all AsrPlan models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AsrPlanSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $query = $dataProvider->query;
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        if(isset($_POST['pageSize'])){
            setcookie('pageSize',$_POST['pageSize']);
        }
        if(!empty($_COOKIE['pageSize'])){
            $pages->pageSize = (int)$_COOKIE['pageSize'];
        }else {
            $pages->pageSize = 1;
        }
        $dataProvider->pagination = $pages;
        //$this->pagesDo($dataProvider);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
//            'pages' => $pages,
        ]);
    }

    /**
     * Displays a single AsrPlan model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
//        $models = AsrCustomer::find()->where(['mobile_id'=>$model->mobile_id])->asArray()->all();
//        //var_dump($model);
//        $searchModel = new AsrPlanSearch();
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//        $query = $dataProvider->query;
//        $countQuery = clone $query;
//        $pages = new Pagination(['totalCount' => $countQuery->count()]);
//        if(isset($_POST['pageSize'])){
//            setcookie('pageSize',$_POST['pageSize']);
//        }
//        if(!empty($_COOKIE['pageSize'])){
//            $pages->pageSize = (int)$_COOKIE['pageSize'];
//        }else {
//            $pages->pageSize = 1;
//        }
//        $dataProvider->pagination = $pages;
        return $this->render('view', [
//            'searchModel' => $searchModel,
//            'dataProvider' => $dataProvider,
//            'models'=>$models,
              $model = $this->findModel($id),
        ]);
    }

    /**
     * Creates a new AsrPlan model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new AsrPlan();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->plan_id]);
        }
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing AsrPlan model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            echo Yii::$app->session->setFlash('success','更新成功！');
            return $this->redirect(['index', 'id' => $model->plan_id]);
        }
        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing AsrPlan model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        echo Yii::$app->session->setFlash('danger','删除成功！');
        return $this->redirect(['index']);
    }

    /**
     * Finds the AsrPlan model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AsrPlan the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AsrPlan::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    /**
     * @param $id 为计划ID
     * 点击执行 、 禁用按钮
     */
    public function actionDisable($id)
    {
        try {
            $asrPlanModel = new AsrPlan();
            $asrPlan = $asrPlanModel->find()->where(['plan_id'=>$id])->one();
            //开始点击了按钮就后台做判断点击的按钮是否是点击了执行还是暂停（中止）
            $this->execInBackground("php ../../yii dosomethingcti/back ".$id." ".$asrPlan->state);
            echo 'success';
            exit();
        } catch (\Exception $e) {
            Tools::writeToLog($e);
            exit();
        }
    }

    /**
     * @param $id 为计划ID
     * 点击执行 、 禁用按钮
     */
    public function actionCtiSleeping($audio_id,$plan_id)
    {
        try {
            $this->redis->set("asr_audio:".$audio_id.":asr_plan:plan_id=".$plan_id.":cti_sleeping",1);
            Tools::l("actionCtiSleeping:".$audio_id);
            echo 'success';
            exit();
        } catch (\Exception $e) {
            Tools::writeToLog($e);
            exit();
        }
    }

    /**
     * 数据接收CTI端的数据
     */
    public function actionReceiveFromJavaweb()
    {
        /**
         * 接收到的数据
         * 格式为
         * $b['plan_id'] = 1;
         * $b['state'] = 0;
         * $b['phone_num'] = 4565;
         * $b['customer_id'] = 4565;
         * $b['audio_id'] = 97;
         * $b['mobile_id'] = 97;
         * $b['recog'] = 识别的结果;
         * 转换为的json字符串
         */
        $data = $_POST;
        Tools::writeToLog("actionReceiveFromJavaweb：接受到CTI端识别的数据：".json_encode($data)."-------------->>");
        $asrSearch = new AsrSearch();
        $asrSearch->search_keyword($data);
    }

    /**
     * 挂断电话
     */
    public function actionHangupPhone()
    {
        $data = $_POST;
        Tools::writeToLog("actionHangupPhone：接受到CTI端的挂断电话消息：".json_encode($data)."-------------->>");
        $asrSearch = new AsrSearch();
        $asrSearch->search_keyword($data);
    }


    /**
     * 无论在windows还是linux里面都能实现后台运行
     * @param $cmd
     */
    function execInBackground($cmd) {
        if (substr(php_uname(), 0, 7) == "Windows"){
            $timer =popen("start /B ". $cmd , "r");
            usleep(5);
            pclose($timer);
        }
        else {
            exec($cmd . " > /dev/null &");
        }
    }

}
